package com.acerola.message;

import com.alibaba.fastjson2.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @program: Chatting
 * @description:
 * @author: Acerola
 * @create: 2022-12-03 11:31
 **/
@Slf4j
public class MessageCode extends ByteToMessageCodec<Message> {

    /**
     * 编码
     *
     * @param channelHandlerContext
     * @param message
     * @param byteBuf
     * @throws Exception
     */
    @Override
    public void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
        //1.4字节的魔数
        byteBuf.writeBytes(new byte[]{1, 2, 3, 4});
        //2.1字节的版本号
        byteBuf.writeByte(1);
        //3.1字节的指令类型
        byteBuf.writeByte(message.getMessageType());
        //4.1字节的序列化方式 jdk 0 ,json 1
        byteBuf.writeByte(0);
        //5.4字节的请求序号
        byteBuf.writeInt(message.getSequenceId());
        //无意义,凑个整数
        byteBuf.writeByte(0xff);
        //6.获取内容的字节数组
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
//        objectOutputStream.writeObject(message);
//        byte[] bytes = byteArrayOutputStream.toByteArray();
        byte[] bytes1 = JSON.toJSONBytes(message);
        //7.获取长度
        byteBuf.writeInt(bytes1.length);
        //8.写入消息正文
        byteBuf.writeBytes(bytes1);
    }

    /**
     * 解码
     *
     * @param channelHandlerContext
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int magicNum = byteBuf.readInt();
        byte version = byteBuf.readByte();
        byte messageType = byteBuf.readByte();
        byte serializerType = byteBuf.readByte();
        int sequenceId = byteBuf.readInt();
        byteBuf.readByte();
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes, 0, length);
//        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
//        Message message = (Message) ois.readObject();
        Message message = JSON.parseObject(bytes, LoginRequestMessage.class);
        log.debug("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, length);
        log.debug("{}", message);
        System.out.println(message);
        list.add(message);
    }
}
